import 'package:dio/dio.dart';
import 'package:enjoy_plus_three/utils/eventbus.dart';
import 'package:enjoy_plus_three/utils/token.dart';
import 'package:flutter/material.dart';

class NetworkService {

  //创建dio实例
  final _dio  = Dio();

  //配置dio实例参数
  NetworkService(){
    //配置基地址
    _dio.options.baseUrl = 'https://live-api.itheima.net';
    //设置连接超时时间
    _dio.options.connectTimeout = const Duration(seconds: 5);
    //设置接收超时时间
    _dio.options.receiveTimeout = const Duration(seconds: 5);
    //设置请求头
    _dio.options.headers = {'Content-Type': 'application/json'};
    //添加请求和响应拦截器
    _addInterceptors();
  }

  //get请求
  //url:请求地址
  //params:请求参数
  Future get(String url,{Map<String,dynamic>? params}) async{
    try {
      final response = await _dio.get(url,queryParameters: params);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }

  //post请求
  //url:请求地址
  //data:请求发送的数据
  Future post(String url,dynamic data) async{
    try {
      final response = await _dio.post(url,data: data);
      return handleResponse(response);
    } catch (e) {
      return handleError(e);
    }
  }


  //成功响应
  dynamic handleResponse(Response response){
    if(response.statusCode! >=200 && response.statusCode!<300){
      return response.data;
    }else{
      throw Exception('请求失败,状态码为${response.statusCode}');
    }
  }

  //失败响应
  dynamic handleError(error){
    if(error is DioException){
      if(error.type == DioExceptionType.connectionTimeout
      || error.type == DioExceptionType.receiveTimeout
      ){
        throw Exception('连接超时');
      }else if(error.type == DioExceptionType.badResponse){
        //token失效后清除token并返回到登录页
        if(error.response?.statusCode == 401){
          TokenManager().removeToken();
          //通过事件通知
          eventBus.fire(Logout());
        }else{
        throw Exception('响应错误');
        }
      }  else {
        throw Exception('网络请求错误,$error');
      }
    }else{
      throw Exception('请求失败,未知错误');
    }
  }

  //封装请求拦截器
  _addInterceptors() {
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: ( options,  handler){
        //请求拦截,添加请求头token
        final token = TokenManager().getToken()?? '';
        if(token.isNotEmpty) {
          options.headers['Authorization'] = 'Bearer $token';
        }
        return handler.next(options);
      },
        onResponse: (response, handler) {
        // 响应拦截器：统一处理成功响应
        return handler.next(response);
      },
        onError: (DioException error, handler) {
        // 响应拦截器：统一处理错误响应
        return handler.next(error);
      },
    ));
  }
}
//导出实例
final http = NetworkService();